﻿using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.DependencyInjection;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using System.Linq;
namespace OrderTrace
{
    public class OrderTraceManager : DomainService, ITransientDependency
    {



        public ITpopf001DapperRepository repositoryTpopf001 { get; set; }

        public ITpopf002DapperRepository repositoryTpopf002 { get; set; }

        public OrderTraceManager(ITpopf001DapperRepository repositoryTpopf001, ITpopf002DapperRepository repositoryTpopf002)
        {

            this.repositoryTpopf001 = repositoryTpopf001;
            this.repositoryTpopf002 = repositoryTpopf002;
        }




        /// <summary>
        /// 准发计划
        /// </summary>
        /// <param name="orderTrace001Inputs"></param>
        /// <returns></returns>
        public async Task<OrderTraceResult> OrderTace001(List<OrderTrace001Input> orderTrace001Inputs)
        {

            var rs = new OrderTraceResult() { Message = "", Status = true };

            try
            {

                foreach (var orderTrace001Input in orderTrace001Inputs)
                {


                    if (string.IsNullOrEmpty(orderTrace001Input.OrderNo))
                        throw new Exception($" Order No cannot be Null");
                    ///计划量增加，更新合同状态
                    ///
                    await repositoryTpopf001.UpdateOrderStatus(orderTrace001Input.OrderNo, "56");

                    //更新量


                }

                var lst_Group = orderTrace001Inputs.GroupBy(m => new { m.WholeBackCodeSeq, m.WholeBackLogNo, m.OrderNo }).Select(m => new
                {
                    OrderNo = m.Key.OrderNo,
                    WholeBackLogNo = m.Key.WholeBackLogNo,
                    WholeBackCodeSeq = m.Key.WholeBackCodeSeq,
                    Wt = m.Sum(m => m.Wt)
                });


                //更新汇总量
                foreach (var itemGroup in lst_Group)
                {
                    await repositoryTpopf002.UpdatePlanWt(
                new
                {
                    OrderNo = itemGroup.OrderNo,
                    WholeBackCodeSeq = itemGroup.WholeBackCodeSeq,
                    WholeBackLogNo = itemGroup.WholeBackLogNo,
                    Wt = itemGroup.Wt

                }
                );
                }


            }
            catch (Exception ex)
            {

                rs.Status = false;
                rs.Message = ex.Message;
            }


            return await Task.FromResult(rs);



        }


    }
}
